package com.lizard.schedule.manager;

import com.lizard.schedule.persistence.db.bean.IdGeneratorBean;
import com.lizard.schedule.persistence.db.table.IdGeneratorTbl;

/**
 * 计划本地id生成管理器
 */
public class ScheduleLocalIdGenerator {

    private static ScheduleLocalIdGenerator instance;

    private final int BUFFER = 10;

    /**
     * 是否可用,初始化只用置为可用
     */
    private boolean enable = false;

    private int mLocalId;

    /**
     * 当前buffer下的currentLocalId最大值
     */
    private int mLocalIdMax;

    private ScheduleLocalIdGenerator(){}

    public static ScheduleLocalIdGenerator getInstance(){
        if(instance == null){
            synchronized (ScheduleLocalIdGenerator.class){
                if(instance == null){
                    instance = new ScheduleLocalIdGenerator();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化，AccountManager记录登录以后调用
     */
    public void init(){
        initLocalId();
        enable = true;
    }

    private void initLocalId(){
        IdGeneratorBean idGeneratorBean = IdGeneratorTbl.getInstance()
                .select(AccountManager.getInstance().getUsername(), IdGeneratorBean.TYPE_SCHEDULE_LOCAL_ID);
        if(idGeneratorBean == null){
            idGeneratorBean = new IdGeneratorBean(
                    AccountManager.getInstance().getUsername() == null ? "" : AccountManager.getInstance().getUsername(),
                    IdGeneratorBean.TYPE_SCHEDULE_LOCAL_ID,
                    IdGeneratorBean.GENERATE_ID_DEFAULT);
            IdGeneratorTbl.getInstance().insert(idGeneratorBean);
        }

        mLocalId = idGeneratorBean.getGenerateId();
        mLocalIdMax = mLocalId + BUFFER - 1;

        idGeneratorBean.setGenerateId(idGeneratorBean.getGenerateId() + BUFFER);
        IdGeneratorTbl.getInstance().updateGenerateId(idGeneratorBean);
    }

    /**
     * 获取生成器id，然后生成器中将该id加1
     *
     * @return
     */
    public int getLocalId(){
        if(!enable){
            return 0;
        }
        int ret = mLocalId;
        mLocalId ++;
        if(mLocalId > mLocalIdMax){ // 当前buffer下的id用光，数据库重新分配
            IdGeneratorBean idGeneratorBean = new IdGeneratorBean(
                    AccountManager.getInstance().getUsername(),
                    IdGeneratorBean.TYPE_SCHEDULE_LOCAL_ID,
                    mLocalId + BUFFER
            );
            IdGeneratorTbl.getInstance().updateGenerateId(idGeneratorBean);
            mLocalIdMax = mLocalId + BUFFER - 1;
        }
        return ret;
    }

    /**
     * 注销
     */
    public void unInit(){
        enable = false;
        mLocalId = 0;
    }

}
